#ifndef SERVER_H
#define SERVER_H

#include <sqlite3.h>
#include <stdio.h>
#include <limits.h>
#include "thread_pool.h"
#include "crypto/sm2_keyex.h"
#include "crypto/sm4_crypto.h"
#include "protocol.h"

typedef struct client_context_s
{
    int client_fd;
    int epoll_fd;
    sqlite3 *db;

    int key_exchange_done;
    int auth_done;
    int user_id;
    unsigned char session_token[32];
    sm2_key_pair_t sm2_server_key;
    unsigned char sm2_client_public_x[SM2_MAX_COORDINATE_LEN];
    unsigned char sm2_client_public_y[SM2_MAX_COORDINATE_LEN];
    unsigned char shared_key[SM2_MAX_COORDINATE_LEN];

    char current_upload_server_path[PATH_MAX];
    FILE *upload_file_ptr;
    uint64_t expected_upload_size;
    uint64_t received_upload_size;
    int upload_in_progress;
    uint32_t current_upload_id;
    unsigned char upload_session_iv[SM4_IV_SIZE];
    int iv_received_for_upload;

    // Download state variables
    FILE *download_file_ptr;
    char current_download_server_path[PATH_MAX];
    uint64_t expected_download_size;
    uint64_t sent_download_size;
    int download_in_progress;
    uint32_t current_download_id;
    unsigned char download_session_iv[SM4_IV_SIZE]; // IV for encrypting download data
    int iv_sent_for_download;                       // Flag to track if IV has been sent for current download

    int marked_for_close;
} client_context_t;

// Function declaration for the client event processing
void process_client_event(void *arg);

int server_init(int port);
int server_accept(int sockfd);
void server_cleanup(int sockfd);

void init_server_thread_pool(int min_threads, int max_threads, int queue_size);
void destroy_server_thread_pool();
thread_pool_t *get_server_thread_pool();

#endif